﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThoughtWorks.QRCode.Codec;

namespace BrnMall.Core.Helper
{
    public class QRCodeHelper
    {
        private static Bitmap GetQRCodeImg(string writeStr)
        {
            QRCodeEncoder qRCodeEncoder = new QRCodeEncoder();
            qRCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//设置二维码编码格式 
            qRCodeEncoder.QRCodeScale = 4;//设置编码测量度             
            qRCodeEncoder.QRCodeVersion = 7;//设置编码版本   
            qRCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//设置错误校验 
            Bitmap image = qRCodeEncoder.Encode(writeStr);
            return image;
        }

        private static Bitmap GetLogoImg(string Path)
        {
            Bitmap newBmp = new Bitmap(Path + @"\qrlogo.jpg");//获取图片对象             
            Bitmap bmp = new Bitmap(newBmp, 30, 30);//缩放             
            return bmp;
        }

        public static string SaveQRCodeImg(string qrText, string logoPath)
        {
            string qrname = Guid.NewGuid().ToString().Replace("-", "") + ".jpg";
            string qrpath = logoPath + @"\qrcode\" + qrname;
            string qrurl = "/images/qrcode/" + qrname;
            try
            {
                Bitmap bCode = GetQRCodeImg(qrText); //获取二维码图片                 
                Bitmap bLogo = GetLogoImg(logoPath);//获取logo图片对象                     
                int Y = bCode.Height;
                int X = bCode.Width;
                Point point = new Point(X / 2 - 15, Y / 2 - 15);//logo图片绘制到二维码上，这里将简单计算一下logo所在的坐标                      
                Graphics g = Graphics.FromImage(bCode);//创建一个画布                     
                g.DrawImage(bLogo, point);//将logo图片绘制到二维码图片上                    
                bCode.Save(qrpath);
            }
            catch (Exception ex)
            {
                qrurl = "";
            }
            return qrurl;
        }

        /// <summary>
        /// 生成二维码转换为base64字符串
        /// </summary>
        /// <param name="qrText"></param>
        /// <returns></returns>
        public static string CreateQRCodeImgToBase64(string qrText)
        {
            string strbaser64 = "";
            try
            {
                Bitmap bmp = GetQRCodeImg(qrText); //获取二维码图片
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                strbaser64 = Convert.ToBase64String(arr);
            }
            catch (Exception)
            {
                throw new Exception("Something wrong during convert!");
            }
            return strbaser64;
        }
    }
}
